﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MongoDB.Driver;
using System.Configuration;

namespace Shop.Data.Mongo
{
    internal static class Util
    {
        /// <summary>
        /// The default key MongoRepository will look for in the App.config or Web.config file.
        /// </summary>
        private const string DefaultConnectionstringName = "MongoServerSettings";

        /// <summary>
        /// Retrieves the default connectionstring from the App.config or Web.config file.
        /// </summary>
        /// <returns>Returns the default connectionstring from the App.config or Web.config file.</returns>
        public static string GetDefaultConnectionString()
        {
            return ConfigurationManager.ConnectionStrings[DefaultConnectionstringName].ConnectionString;
        }

        /// <summary>
        /// Creates and returns a MongoDatabase from the specified url.
        /// </summary>
        /// <param name="url">The url to use to get the database from.</param>
        /// <returns>Returns a MongoDatabase from the specified url.</returns>
        public static MongoDatabase GetDatabaseFromUrl(MongoUrl url)
        {
            MongoServer server = MongoServer.Create(url.ToServerSettings());
            return server.GetDatabase(url.DatabaseName);
        }

        public static MongoDatabase GetDatabaseFromUrl(string connectionstring)
        {
            MongoUrl url = new MongoUrl(connectionstring);
            return GetDatabaseFromUrl(url);
        }
    }
}
